import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Button,
  Modal,
  Form,
  message,
  Input,
  Icon,
  Drawer,
  Menu, Dropdown, Select, TreeSelect, Popover, Tooltip, DatePicker
} from 'antd';
import moment from 'moment'
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';

import debounce from 'lodash/debounce';
import {
  renderValveOpen,
  afterCloseModal,
  renderTreeNodes,
  popoverPrice,
  download,
  formateObjToParamStr,formateObjToParamStr2,renderSignalIntensity,
  getEW
} from '@/utils/utils';
import BuildModalTitle from '@/components/BuildModalTitle';
import Detail from './Detail';
import PayForm from './OwnerPay';
import ChangeMeter from './ChangeMeter';
import ReactDataGrid from 'react-data-grid';
import AddOrEditOwner from './AddOrEditOwner';
import AddOrEditAccount from './AddOrEditAccount';
import ExportMeterData from './ExportMeterData';
import ChangeInitValue from './ChangeInitValue';
import Area from './Area';
import request from '@/utils/request';
import stop from './../../images/stop.png'
import config from '../../config/config'
import wechat from '@/images/wechat.png';
import jsyh from '@/images/jsyh.png';
import gold from '@/images/gold.png';
import Highlighter from 'react-highlight-words';
import {routerRedux} from "dva/router";
import AreaMap from "@/components/AreaMap";
const { confirm } = Modal;
const FormItem = Form.Item;
const InputGroup = Input.Group;
const Option = Select.Option;

let resetConfirm;
@connect(({ owner, loading, global }) => ({
  owner,
  global,
  loading: loading.models.owner,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      data: [],
      selectedRowKeys: [],
      price_nature: [],
      mode:"1",
      all_vendors: [],
      monthPay:''
    };
  }


  componentDidMount() {
    const { dispatch } = this.props;
    const {
      owner: { pageLoaded, scrollData,searchParams },
    } = this.props;

    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        owner: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'owner/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'owner/changeLoaded',
          });
          dispatch({
            type: 'owner/changeTableY',
          });
        },
      });

    }
    const that = this;
    request(`/all_regions`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }

    });
    request(`/all_vendors`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_vendors: response.data.data,
        });
      }

    });
    request(`/all_price_natures`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          price_nature: response.data.data,
        });
      }

    });
    this.fetPayments()
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    // document.addEventListener('keyup',this.keyupFunc)

  }
  keyupFunc=(e)=>{
    if(e.keyCode===13) {
      this.searchFunc()
    }
  }
  fetPayments=()=>{
    const that=this;
    request(`/payments`, {
      method: 'GET',
      params:{
        communication_type:1,
        start_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD").format("YYYY-MM-DD"),
        end_date:moment(new Date()).format('YYYY-MM-DD'),
      }
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          monthPay: response.data.summary.total_amount,
        });
      }

    });
  }
  searchFunc=()=>{
    const that=this
    const { form , owner: { searchParams}} = that.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.log('fieldsValue',fieldsValue)
      that.handleSearch({
        page: 1,
        per_page: searchParams.per_page,
        ...fieldsValue,
        region_id:fieldsValue.region_id?fieldsValue.region_id.split('$')[0]:'',
        region_name:fieldsValue.region_id?fieldsValue.region_id.split('$')[1]:'',
        start_date: fieldsValue.start_date ? moment(fieldsValue.start_date).format('YYYY-MM-DD') : '',
        end_date: fieldsValue.end_date ? moment(fieldsValue.end_date).format('YYYY-MM-DD') : '',
        filter_level:'',
        filter_year:'',
      },function() {
        const {
          owner: { scrollData },
        } = that.props;
        const table = document.querySelector('.react-grid-Canvas');
        if(table){
          setTimeout(() => {
            table.scrollTop = 0;
            table.scrollLeft = scrollData.x;
          }, 0);
        }
      });

    });
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'owner/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'owner/changeTableY',
    });
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    // document.removeEventListener('keyup',this.keyupFunc);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  findChildFunc = (cb) => {
    this.findChildLocation = cb;
  };
  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    const {
      owner: {searchInputType,searchInputText },
    } = this.props;
    dispatch({
      type: 'owner/fetch',
      payload: {
        ...values,
        [searchInputType]:searchInputText
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
    that.fetPayments()
  };

  renderSimpleForm() {
    const data = this.state.data;
    const { dispatch } = this.props;
    const {
      owner: { searchParams, selectedRowKeys,searchInputType,searchInputText },
    } = this.props;
    const form=this.props.form
    const getFieldDecorator=form.getFieldDecorator
    return (
      <Form layout="inline" className="search-form">

        <AreaMap form={form} searchParams={searchParams} getFieldDecorator={getFieldDecorator}/>
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: searchParams.start_date ? moment(searchParams.start_date) : '',
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={true}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: searchParams.end_date ? moment(searchParams.end_date) : '',
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={true}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label="区域">
          {getFieldDecorator('region_id', {
            initialValue: searchParams.region_id?`${searchParams.region_id}$${searchParams.region_name}`:'',
          })(
            <TreeSelect
              style={{ width: '100px' }}
              allowClear
              treeDefaultExpandAll
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              showSearch
            >
              {renderTreeNodes(data)}
            </TreeSelect>,
          )}
        </FormItem>
        <FormItem label="所属片区">
          {getFieldDecorator('region_area', {
            initialValue: searchParams.region_area,
          })(<Select style={{width:'90px'}}  allowClear={true}>
            <Option value={'A片区'}>A片区</Option>
            <Option value={'B片区'}>B片区</Option>
            <Option value={'C片区'}>C片区</Option>
            <Option value={'D片区'}>D片区</Option>
          </Select>)}
        </FormItem>
        <FormItem label="水表厂商">
          {getFieldDecorator('vendor_id', {
            initialValue: searchParams.vendor_id,
          })(
            <Select style={{ width: '120px' }} allowClear >
              {
                this.state.all_vendors.map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="状态">
          {getFieldDecorator('status', {
            initialValue: searchParams.status,
          })(<Select style={{width:'90px'}}>
            <Option value={'0'}>全部</Option>
            <Option value={'1'}>正常</Option>
            <Option value={'-1'}>注销</Option>
          </Select>)}
        </FormItem>
        <FormItem label="余额状态">
          {getFieldDecorator('balance_status', {
            initialValue: searchParams.balance_status,
          })(<Select style={{width:'90px'}}>
            <Option value={'0'}>全部</Option>
            <Option value={'1'}>正常</Option>
            <Option value={'-1'}>欠费</Option>
          </Select>)}
        </FormItem>
        <FormItem label="口径">
          {getFieldDecorator('caliber', {
            initialValue: searchParams.caliber,
          })(   <Select style={{width:'100px'}}>
            {[{key:'全部',value:''},
              {key:'未知',value:'未知'},
              {key:'DN15',value:'DN15'},
              {key:'DN20',value:'DN20'},
              {key:'DN25',value:'DN25'},
              {key:'DN32',value:'DN32'},
              {key:'DN40',value:'DN40'},
              {key:'DN50',value:'DN50'},
              {key:'DN65',value:'DN65'},
              {key:'DN80',value:'DN80'},
              {key:'DN100',value:'DN100'},
              {key:'DN150',value:'DN150'},
              {key:'DN200',value:'DN200'},
              {key:'DN300',value:'DN300'},
            ].map(function(item,index) {
              return <Option key={index} value={item.value}>
                {item.key}
              </Option>
            })}
          </Select>)}
        </FormItem>
        <FormItem label="户主性质">
          {getFieldDecorator('account_nature', {
            initialValue: searchParams.account_nature,
          })(   <Select style={{width:'120px'}}>
            {[{key:'全部',value:''},
              {key:'个人',value:'个人'},{key:'个体工商户',value:'个体工商户'},
              {key:'企业',value:'企业'},{key:'政府机关',value:'政府机关'},{key:'教育系统',value:'教育系统'},
              {key:'医疗机构',value:'医疗机构'},{key:'事业单位',value:'事业单位'},
              {key:'军队',value:'军队'},{key:'社会团体',value:'社会团体'},
              {key:'国防机构',value:'国防机构'}, {key:'集体经济',value:'集体经济'},{key:'宗教团体',value:'宗教团体'},
              {key:'民办非企业单位',value:'民办非企业单位'},{key:'律师执业机构',value:'律师执业机构'},
              {key:'基金会',value:'基金会'},{key:'公正机构',value:'公正机构'},
              {key:'外国在华文化中心',value:'外国在华文化中心'},{key:'群众性团体组织',value:'群众性团体组织'},
              {key:'司法鉴定机构',value:'司法鉴定机构'},{key:'仲裁机构',value:'仲裁机构'},
              {key:'境外机构',value:'境外机构'},{key:'其他',value:'其他'}
            ].map(function(item,index) {
              return <Option key={index} value={item.value}>
                {item.key}
              </Option>
            })}
          </Select>)}
        </FormItem>
        <FormItem label="居民类型">
          {getFieldDecorator('resident_type', {
            initialValue: searchParams.resident_type,
          })(   <Select style={{width:'80px'}}>
            {[{key:'全部',value:''},
              {key:'居民',value:'1'},{key:'非居民',value:'2'},
            ].map(function(item,index) {
              return <Option key={index} value={item.value}>
                {item.key}
              </Option>
            })}
          </Select>)}
        </FormItem>
        <FormItem
          label={'用水性质'}
        >
          {getFieldDecorator(`price_nature_id`, {
            initialValue:  searchParams.price_nature_id,

          })(
            <Select  style={{width:'140px'}} dropdownMatchSelectWidth={false}>
              <Option value={''}>
              全部
              </Option>
              {
                this.state.price_nature.map((item,index)=>{
                  return <Option title={item.name} key={index} value={item.id}>
                    <Highlighter
                      highlightClassName="YourHighlightClass"
                      searchWords={["有下水"]}
                      highlightStyle={{backgroundColor:'#fdffd0',padding:'0'}}
                      autoEscape={true}
                      textToHighlight= {item.name}
                    /></Option>
                })
              }
            </Select>
          )}
        </FormItem>
        <FormItem>
          <InputGroup compact>
            <Select onChange={(e)=>{
              dispatch({
                type: 'owner/changeOneProperty',
                payload: {
                  searchInputType:e
                },
              });
            }} style={{ width: '100px',color:'#000' }}  value={searchInputType}>
              <Option value="mobile">户主手机</Option>
              <Option value="name">户主姓名</Option>
              <Option value="meter_number">水表号</Option>
              <Option value="address">地址</Option>
            </Select>
            <Input style={{ width: '130px' }} value={searchInputText}  onKeyPress={this.keyPress} onChange={(e)=>{
              dispatch({
                type: 'owner/changeOneProperty',
                payload: {
                  searchInputText:e.target.value
                },
              });
            }} />
          </InputGroup>
        </FormItem>
   {/*     <FormItem label="户主姓名">
          {getFieldDecorator('name', {
            initialValue: searchParams.name,
          })(<Input style={{ width: '130px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="户主手机">
          {getFieldDecorator('mobile', {
            initialValue: searchParams.mobile,
          })(<Input style={{ width: '130px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('meter_number', {
            initialValue: searchParams.meter_number,
          })(<Input style={{ width: '130px' }} placeholder="请输入"/>)}
        </FormItem>*/}

        <FormItem>
          <Button
            id={'SEARCH_BTN'}
            type="primary"
            icon='search'
            onClick={() => {
              this.searchFunc()
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>

        </FormItem>

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        owner: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.searchFunc()

      });
    }
  }
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'owner/add',
      payload: {
        ...formValues,
        region_id:formValues.region_id?formValues.region_id.split('$')[0]:'',
      },
      callback() {
        message.success('添加远传表户主成功');
        that.setState({
          addModal: false,
        });
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form,dispatch } = this.props;
    form.resetFields();
    const that = this;
    dispatch({
      type: 'owner/changeOneProperty',
      payload: {
        searchInputType:'mobile',
        searchInputText:'',
        searchParams:{
          region_id:"",
          region_name:'',
          region_area:"",
          resident_type:'',
          account_nature:"",
          status:'0',
          vendor_id:'',
          balance_status:'0',
          price_nature_id:'',
          caliber:'',
          name:'',
          company_id:'',
          mobile:'',
          meter_number:'',
          address:'',
          filter_level:'',
          filter_year:'',
          page: 1,
          per_page: 50,
        },
      },
      callback(){
        that.handleSearch({
          region_id: '',
          region_name: '',
          region_area:"",
          status:'0',
          caliber:'',
          price_nature_id:'',
          balance_status:'0',
          filter_level:'',
          filter_year:'',
          address:'',
          page: 1,
          per_page: 50,
        });
      }
    });

  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `owner/edit`,
      payload: {
        ...formValues,
        region_id:formValues.region_id?formValues.region_id.split('$')[0]:'',
        id: this.state.editRecord.id,

      },
      callback() {
        message.success('修改户主成功');
        that.setState({
          editModal: false,
        });
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleExport=()=>{
    const formValues = this.exportForm.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const payload= {
      meter_id:this.state.editRecord.meter_number,
      start_date:moment(formValues.start).format('YYYY-MM-DD'),
      end_date:moment(formValues.end).format('YYYY-MM-DD')
    }
    download(`${config.prefix}/meter_data_files?Authorization=Bearer ${sessionStorage.getItem('token')}&${formateObjToParamStr(payload)}`)

  }
  handleExportOwner=()=>{
    const {
      owner: { searchParams },
    } = this.props;
    console.log('searchParams',searchParams)
    download(`${config.prefix}/account_files?Authorization=Bearer ${sessionStorage.getItem('token')}&order_direction=desc&${formateObjToParamStr2({...searchParams,
      company_ids:getEW(searchParams.company_ids)})}`)

  }
  onRowsSelected = (rows) => {
    const {
      owner: { selectedRowKeys },
    } = this.props;
    this.props.dispatch({
      type: 'owner/changeSelectRow',
      payload: selectedRowKeys.concat(rows.map(r =>  r.rowIdx)),
    });
  };
  onRowsDeselected = (rows) => {
    let rowIndexes = rows.map(r => r.rowIdx);
    const {
      owner: { selectedRowKeys },
    } = this.props;
    this.props.dispatch({
      type: 'owner/changeSelectRow',
      payload: selectedRowKeys.filter(i => rowIndexes.indexOf(i) === -1),
    });
  };
  ChangeValve = (value) => {
    if (value === 1) {
      this.setState({
        openValveLoading: true,
      });
    } else {
      this.setState({
        closeValveLoading: true,
      });
    }
    const that = this;
    const {
      owner: { data, selectedRowKeys },
    } = this.props;
    console.log('selectedRowKeys', selectedRowKeys);
    let meter_ids = [];
    for (let i = 0; i < data.length; i++) {
      if (selectedRowKeys.indexOf(i) >= 0) {
        meter_ids.push(data[i].meter_number);
      }
    }
    console.log('meter_ids', meter_ids);
    request(`/meter_valve_switch`, {
      method: 'POST',
      data: {
        meter_ids: meter_ids,
        valve_status: value,
      },
    }).then((response) => {
      if (response.status === 200) {
        message.success(`${value === 1 ? '开阀' : '关阀'}指令下发成功`);

      }
      setTimeout(function() {
        that.setState({
          openValveLoading: false,
          closeValveLoading: false,
        });
      }, 5000);
    });
  };
  handleEditAccount = () => {
    const that = this;
    const formValues = this.EditAccountForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    request(`/accounts/${this.state.editRecord.id}`, {
      method: 'PUT',
      data: formValues,
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          editMeterModal: false,
        });
        message.success('修改成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  };
  handleChangeInit= () => {
    const that = this;
    const formValues = this.changeInitForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    request(`/accounts/${this.state.editRecord.id}/initial_value`, {
      method: 'POST',
      data: {
        initial_value:formValues.initial_value
      },
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          changeInitModal: false,
          editRecord:{}
        });
        message.success('修改水表底数成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  };
  handleReset=(id)=>{
    const that=this;
    resetConfirm.update({
      title: '正在重新扣费',
      content: <h3>请稍等...</h3>,
      maskClosable:false,
      cancelButtonProps:{
        disabled:true
      }
    });
    request(`/accounts/${id}/reset`, {
      method: 'POST',
      data:{
        mode:Number(this.state.mode)
      }
    }).then((response) => {
      if (response.status === 200) {
        resetConfirm.destroy();
        message.success('重新扣费成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);

      }
    });
    setTimeout(function (){
      resetConfirm.destroy();
    },15000)
  }
  handleSettle=(id)=>{
    const that=this;
    request(`/accounts/${id}/settle`, {
      method: 'POST',
    }).then((response) => {
      if (response.status === 200) {
        message.success('立即扣费成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleDisable=(id)=>{
    const that=this;
    request(`/accounts/${id}/disable`, {
      method: 'POST',
    }).then((response) => {
      if (response.status === 200) {
        message.success('注销账户成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleResetPassword=(mobile)=>{
    const that=this;
    request(`/mobile_password/reset`, {
      method: 'POST',
      data:{
        mobile:mobile
      }
    }).then((response) => {
      if (response.status === 200) {
        message.success('重置微信公众号密码成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleAllowPayment=(id,value)=>{
    const that=this;
    request(`/accounts/${id}/allow_payment`, {
      method: 'POST',
      data:{
        allow_payment:value
      }
    }).then((response) => {
      if (response.status === 200) {
        message.success('操作成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }

  handleClickPayment = (key) => {
    console.log('key)', key);
    const {panes, routerMapping} = this.props.global;
    const {dispatch} = this.props;
    const activeKey = key;
    const that = this;
    if (find(panes, o => o.key == activeKey)) {
      console.log('已经存在');
    } else {
      panes.push({
        title: find(routerMapping, o => o.path == activeKey).name,
        content: 'New Tab Pane',
        key: activeKey,
      });
    }
    dispatch(routerRedux.push(activeKey));
    dispatch({
      type: 'global/changePanesAndActive',
      payload: {panes, activeKey},
      callback: function () {
        const sendSearchParams = {
          start_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD").format("YYYY-MM-DD"),
          end_date:moment(new Date()).format('YYYY-MM-DD'),
          region_id: "",
          name: '',
          communication_type:"1",
          mobile: '',
          date_type: "generation_date",
          meter_number: '',
          operator_name: '',
          type: '',
          invoicing_status: '',
          page: 1,
          per_page: 50,
          id: '',
          operator_id: ''
        };
        console.log('sendSearchParams', sendSearchParams);
        dispatch({
          type: 'payment/changeLoadedFalse',
          callback: function () {
            dispatch({
              type: 'payment/changeSearchParams',
              payload: sendSearchParams,
            });
          }
        });

      }
    });
  };

  render() {
    const that = this;
    const {
      owner: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global: { gridTableW },
    } = this.props;
    const defaultColumnProperties = {
      resizable: true,
    };
    const username = sessionStorage.getItem('username')
    const renderMenuItem=function(row) {
      return <Menu onClick={({ key })=>{
        console.log('key',key)
        if(key === 'edit'){
          that.setState({
            editRecord: row,
            editModal: true,
          });
        }else if(key === 'change'){
          that.setState({
            editRecord: row,
            changeModal: true,
          });
        }else if(key === 'export'){
          that.setState({
            editRecord: row,
            exportModal: true,
          });
        }else if(key === 'changeInit'){
          that.setState({
            editRecord: row,
            changeInitModal: true,
          });
        }else if(key === 'reset'){
          resetConfirm=confirm({
            title: `确定要对 "${row.meter_number}" 重新扣费吗?`,
            content: <div><div>请选择模式 : <Select style={{width:'210px'}} defaultValue={that.state.mode}  onChange={(e) => {
              that.setState({
                mode: e
              })
            }}>
              <Option value={'1'}>
                按当前用水性质扣费
              </Option>
              <Option value={'2'}>
                按历史用水性质扣费
              </Option>
            </Select>
            </div> 请谨慎操作！ </div>,
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            centered:true,
            maskClosable: true,
            onOk() {
              that.handleReset(row.id);
              return new Promise((resolve, reject) => {
                reject
              })
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }else if(key === 'settle'){
          confirm({
            title: `确定要对 "${row.meter_number}" 立即扣费吗?`,
            content: '请谨慎操作！',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            centered:true,
            maskClosable: true,
            onOk() {
              that.handleSettle(row.id);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }else if(key === 'disable'){
          confirm({
            title: `确定要注销 "${row.meter_number}" 账户吗?`,
            content: '请谨慎操作！',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            centered:true,
            maskClosable: true,
            onOk() {
              that.handleDisable(row.id);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }else if(key === 'reset_mobile_password'){
          confirm({
            title: `确定要重置 "${row.mobile}" 微信公众号密码吗?`,
            content: '请谨慎操作！',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            centered:true,
            maskClosable: true,
            onOk() {
              that.handleResetPassword(row.mobile);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }else if(key === 'pause_payment'){
          confirm({
            title: `确定要"${row.allow_payment===1?"暂停充值":"恢复充值"}"吗?`,
            content: '请谨慎操作！',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            centered:true,
            maskClosable: true,
            onOk() {
              that.handleAllowPayment(row.id,row.allow_payment===1?-1:1);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }

      }
      }>
      {
        find(that.permissions, { name: 'meter_data_export' }) &&
        <Menu.Item key={'export'}>
          导出水表读数
        </Menu.Item>
      }

        {
          find(that.permissions, { name: 'account_add_and_edit' }) &&
          <Menu.Item key={'edit'}>
            编辑
          </Menu.Item>
        }
        {
          find(that.permissions, { name: 'meter_replace' }) &&
          <Menu.Item key={'change'}>
            换表
          </Menu.Item>
        }
        {
          find(that.permissions, { name: 'initial_value_edit' }) &&
          <Menu.Item key={'changeInit'}>
            修改水表底数
          </Menu.Item>
        }
        {
          find(that.permissions, { name: 'account_reset' })&&
          <Menu.Item key={'settle'}>
            账户立即扣费
          </Menu.Item>
        }
        {
          find(that.permissions, { name: 'account_settle' })&&
          <Menu.Item key={'reset'}>
            <span style={{color:'red'}}>账户重新扣费</span>
          </Menu.Item>
        }
        {
          find(that.permissions, { name: 'account_disable' })&&
          <Menu.Item key={'disable'}>
            <span style={{color:'red'}}>注销</span>
          </Menu.Item>
        }
        {
          find(that.permissions, { name: 'reset_mobile_password' })&&
          <Menu.Item key={'reset_mobile_password'}>
            <span style={{color:'#00c10b'}} title={'默认密码为：123456'}>重置公众号密码</span>
          </Menu.Item>
        }
        {
          find(that.permissions, { name: 'pause_payment' })&&
          <Menu.Item key={'pause_payment'}>
            <span style={{color:row.allow_payment===1?"red":"green"}} >{row.allow_payment===1?"暂停充值":"恢复充值"}</span>
          </Menu.Item>
        }
      </Menu>
    }
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            owner: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '户主姓名',
        key: 'name',
        width: 180,
        frozen: true,
        formatter: (event) => {
          return <span title={event.row.name}
                       style={{cursor:'pointer',color:'#299100'}}
                       onClick={(e) => {
                         this.setState({
                           editRecord: event.row,
                           infoModal: true,
                         });
                       }}
          >{event.row.name}</span>;
        },
      },
      {
        name: '户主手机',
        key: 'online_status',
        frozen: true,
        width: 100,
        formatter: (event) => {
          return <span title={event.row.mobile}>{event.row.mobile}</span>;
        },
      },
      {
        name: '账户余额',
        width: 90,
        frozen: true,
        key: 'balance',
        formatter: (event) => {
          return <p
            className={Number(event.value) > Number(event.row.balance_alarm_amount) ? 'table-success table-status' :
              Number(event.value) >= 0 ? 'table-warm table-status' : 'table-error table-status'}>{event.value}</p>;
        },
      },
      {
        name: '户主地址',
        width: 200,
        key: 'address',
        formatter: (event) => {
          return <span title={event.row.address}>{event.row.address}</span>;
        },
      },
      {
        name: '户主性质',
        width: 80,
        key: 'account_nature',
      },
      {
        name: '用水性质',
        width: 128,
        key: 'price_nature',
        formatter:(event)=>{
          return <Popover title={event.row.price_nature.name} content={popoverPrice(event.row.price_nature)}>
            {event.row.price_nature.name}
          </Popover>
        }
      },
      {
        name: '水表号',
        width: 125,
        key: 'meter_number',
        formatter: (event) => {
          return <span title={event.value} style={{color:event.row.status===-1?'red':''}}>
            {event.row.status===-1&& <img style={{width:'22px',height:'22px',top:'-2px',position:'relative'}} src={stop} alt=""/>}
            {event.value}
          </span>;
        },
      },

      {
        name: '上次缴费时间',
        width: 150,
        key: 'last_payment_time',
      },
      {
        name: '缴费金额',
        width: 100,
        key: 'last_payment_amount',
        formatter: (event) => {
          return <div className={`money ${event.value < 0 ? 'error' : ''}`}><img className={'gold'} src={gold}
                                                                                 alt=""/>{event.value}</div>;
        },
      },
      {
        name: '类型',
        width: 120,
        key: 'last_payment_type',
        formatter: (event) => {
          let text = '';
          switch (Number(event.value)) {
            case 1:
              text='现金';
              break;
            case 2:
              text='支票';
              break;
            case 3:
              text='银行卡';
              break;
            case 4:
              text='微信扫码';
              break;
            case 5:
              text='支付宝扫码';
              break;
            case 6:
              text='网银';
              break;
            case 7:
              text='网银2';
              break;
            case 30:
              text='补水';
              break;
            case 11:
              return <span><img style={{ width: '20px', height: '20px', marginRight: '2px' }} src={wechat} alt=""/>公众号缴费</span>;
            case 12:
              return <span><img style={{ width: '20px', height: '20px', marginRight: '2px' }} src={wechat} alt=""/>公众号缴费</span>;
            case 13:
              return <span><img style={{ width: '20px', height: '20px', marginRight: '2px' }} src={jsyh} alt=""/>建行APP缴费</span>;
            case 20:
              text = '撤销缴费';
              break;
            default:
              break;
          }
          return text;
        },
      },
      {
        name: '网银流水号',
        width: 150,
        key: 'last_payment_transaction_serial_number',
      },
      {
        name: '开票状态',
        width: 100,
        key: 'last_payment_invoicing_status',
        formatter: (event) => {
          let type=''
          if(event.row.invoicing_type===1){
            type='(电子)'
          }else if(event.row.invoicing_type===2){
            type='(纸质)'
          }else if(event.row.invoicing_type===4){
            type='(专用)'
          }else if(event.row.invoicing_type===3){
            type='(纸质+专用)'
          }
          let text = '';
          switch (event.value) {
            case -3:
              text = '开票失败';
              break;
            case -2:
              text = '不允许开票';
              break;
            case -1:
              text = '未开票';
              break;
            case 1:
              text = '正在开票';
              break;
            case 2:
              text = '已开票';
              break;
          }
          return <span title={type+text}>{type+text}</span>;
        },
      },
      {
        name: '上次抄表时间',
        width: 150,
        key: 'last_reading_time',
      },
      {
        name: '抄表读值(m3)',
        width: 100,
        key: 'last_reading_value',
      },
      {
        name: '阀门状态',
        key: 'valve_status',
        width: 80,
        formatter: (event) => {
          return renderValveOpen(event.value);
        },
      },
      {
        name: '信号强度',
        key: 'signal_intensity',
        width: 80,
        formatter: (event) => {
          return renderSignalIntensity(event.value);
        },
      },
      {
        name: '开户时间',
        key: 'created_at',
        width: 160,
      },
      {
        name: '操作',
        width: 230,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          {
            find(this.permissions, { name: 'counter_payment2' }) &&<Button
              className={event.row.allow_payment===-1?'':'btn-gold'}
              type="primary"
              icon="pay-circle"
              size="small"
              style={{backgroundColor:event.row.allow_payment===-1?'#b7b7b7;!importent':'' }}
              disabled={Boolean(event.row.allow_payment===-1)}
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  payModal: true,
                });
              }
              }
            >充值
            </Button>
          }
          <Button
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
         {/*  {event.row.status === 1 &&
          <Dropdown overlay={renderMenuItem(event.row)} placement="bottomRight">
            <Button   size="small">更多<Icon type="down" /></Button>
          </Dropdown>
          } */}
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 60;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>远传表档案</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item  animated fadeInLeft">
            <p>已管理远传表数量</p>
            <h4>{meta.total}</h4>
          </div>
          <div className="table-info-item  animated fadeInLeft">
            <Tooltip title={`所有远传表当月充值金额，与表格筛选条件无关`}>  <p style={{color:'green'}}>当月充值总金额
              <Icon style={{marginLeft:'3px'}} type="question-circle"/></p></Tooltip>
            <h4 style={{color:'green',cursor:'pointer'}}
            onClick={()=>{
              this.handleClickPayment('/payment')
            }}>{this.state.monthPay}</h4>
          </div>

          <div size="large" className="table-info-right-item  animated fadeInRight">
            {
              find(this.permissions, { name: 'meter_switch2' }) &&
              <Fragment>
                  <span style={{ marginBottom: 0 }}>已选 {selectedRowKeys.length} 个水表</span>
                  <Button
                    loading={this.state.openValveLoading}
                    type={'primary'} style={{ marginLeft: 8 }} className={'btn-green'} icon='rocket'
                    onClick={(e) => {
                      const that = this;
                      if (selectedRowKeys.length === 0) {
                        message.error('请先选择水表');
                        return false;
                      }
                      confirm({
                        title: `确定要对${selectedRowKeys.length}个水表开阀吗?`,
                        content: '请谨慎操作！',
                        okText: '确定',
                        okType: 'danger',
                        cancelText: '取消',
                        centered: true,
                        maskClosable: true,
                        onOk() {
                          that.ChangeValve(1);
                        },
                        onCancel() {
                          console.log('Cancel');
                        },
                      });
                    }}>
                    批量开阀
                  </Button>
                  <Button type={'danger'}
                          loading={this.state.closeValveLoading}
                          style={{ marginLeft: 8 }} icon='poweroff'
                          onClick={(e) => {
                            const that = this;
                            if (selectedRowKeys.length === 0) {
                              message.error('请先选择水表');
                              return false;
                            }
                            confirm({
                              title: `确定要对${selectedRowKeys.length}个水表关阀吗?`,
                              content: '请谨慎操作！',
                              okText: '确定',
                              okType: 'danger',
                              cancelText: '取消',
                              centered: true,
                              maskClosable: true,
                              onOk() {
                                that.ChangeValve(-1);
                              },
                              onCancel() {
                                console.log('Cancel');
                              },
                            });
                          }}>
                    批量关阀
                  </Button>
              </Fragment>
            }
            {
              find(this.permissions, { name: 'account_export' }) &&
              <Tooltip title={'请先查询一次再导出'}>
                <Button
                  className={'btn-green'}
                  type="primary"
                  icon="export"
                  style={{ marginLeft: 8 }}
                  onClick={this.handleExportOwner}
                >导出远传表档案
                </Button>
              </Tooltip>
            }

            {
              find(this.permissions, { name: 'regions_management2' }) &&
              <Button
                icon="global"
                style={{ marginLeft: 8 }}
                type="primary"
                onClick={
                  () => {
                    this.setState({
                      areaModal: true,
                    });
                  }
                }
              >
                区域管理
              </Button>
            }
            {
              find(this.permissions, { name: 'account_add_and_edit2' }) &&
              <Button
                icon="plus"
                style={{ marginLeft: 8 }}
                type="primary"
                onClick={
                  () => {
                    this.setState({
                      addModal: true,
                    });
                  }
                }
              >
                添加远传表户主
              </Button>
            }

          </div>

        </div>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}

            rowSelection={{
              showCheckbox: true,
              enableShiftSelect: true,
              onRowsSelected: this.onRowsSelected,
              onRowsDeselected: this.onRowsDeselected,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}

          />
          {
            loading && <Loading/>
          }
        </div>
      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          owner: { scrollData },
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop = 0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加远传表档案"/>}
        visible={this.state.addModal}
        centered
        onOk={this.handleAdd}
        width={1000}
        className="addModal"
        onCancel={() => {
          this.setState({ addModal: false });
        }}

      >
        <AddOrEditOwner price_nature={this.state.price_nature} data={this.state.data}
                        wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 ${this.state.editRecord && this.state.editRecord.name} `}/>}
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        destroyOnClose
        width={1000}
        className="editModal"
        onCancel={() => {
          this.setState({ editModal: false });
        }}

      >
        <AddOrEditOwner editRecord={this.state.editRecord} price_nature={this.state.price_nature} data={this.state.data}
                        wrappedComponentRef={(inst) => this.EditForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editMeterModal} modalClass="editMeterModal"
                                title={`修改"${this.state.editRecord.owner && this.state.editRecord.name}"下水表 ${this.state.editRecord.meter_number}`}/>}
        visible={this.state.editMeterModal}
        centered
        onOk={this.handleEditAccount}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        destroyOnClose
        className="editMeterModal"
        onCancel={() => {
          this.setState({ editMeterModal: false });
        }}

      >
        <AddOrEditAccount editRecord={this.state.editRecord} price_nature={this.state.price_nature}
                          wrappedComponentRef={(inst) => this.EditAccountForm = inst}/>

      </Modal>
      <Drawer
        title={`${this.state.editRecord && this.state.editRecord.name} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={780}
        visible={this.state.infoModal}

      >
        <Detail meter_number={this.state.editRecord.meter_number}
                id={this.state.editRecord.id}></Detail>
      </Drawer>
      <Modal
        title={<BuildModalTitle visible={this.state.payModal} modalClass="payModal"
                                title={`${this.state.editRecord && this.state.editRecord.name} 充值`}/>}
        destroyOnClose
        visible={this.state.payModal}
        centered
        onOk={this.handleConfig}
        className="payModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={700}
        onCancel={() => {
          this.setState({ payModal: false, editRecord: {} });
        }}
        footer={[]}

      >
        <PayForm editRecord={this.state.editRecord} handleSearch={this.handleSearch}
                 wrappedComponentRef={(inst) => this.payForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.changeModal} modalClass="changeModal"
                                title={`${this.state.editRecord && this.state.editRecord.name} 换表`}/>}
        destroyOnClose
        visible={this.state.changeModal}
        centered
        onOk={this.handleConfig}
        className="changeModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={700}
        onCancel={() => {
          this.setState({ changeModal: false, editRecord: {} });
        }}
        footer={[]}

      >
        <ChangeMeter editRecord={this.state.editRecord} handleSearch={this.handleSearch}
                     wrappedComponentRef={(inst) => this.payForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.changeInitModal} modalClass="changeInitModal"
                                title={`${this.state.editRecord && this.state.editRecord.name} 修改水表底数`}/>}
        destroyOnClose
        visible={this.state.changeInitModal}
        centered
        onOk={this.handleChangeInit}
        className="changeInitModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={700}
        onCancel={() => {
          this.setState({ changeInitModal: false, editRecord: {} });
        }}

      >
        <ChangeInitValue editRecord={this.state.editRecord}
                     wrappedComponentRef={(inst) => this.changeInitForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.exportModal} modalClass="exportModal"
                                title={`导出 ${this.state.editRecord && this.state.editRecord.name} 水表数据`}/>}
        destroyOnClose
        visible={this.state.exportModal}
        centered
        onOk={this.handleExport}
        className="exportModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ exportModal: false, editRecord: {} });
        }}

      >
        <ExportMeterData editRecord={this.state.editRecord}
                     wrappedComponentRef={(inst) => this.exportForm = inst}/>
      </Modal>
      <Drawer
        title={`区域管理`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            areaModal: false,
            editRecord: {},
          });
        }}

        width={780}
        visible={this.state.areaModal}
      >
        <Area/>
      </Drawer>
    </div>;
  }
}

export default BasicList;
